// pages/comment/index.js
var common = require("../../../public.js");
Page({
  data: {
    content: [],
    fileList: [],
    orderInfo: '',
    autosize: {
    maxHeight: 100,
     minHeight: 50
    }
  },
  onLoad: function (options) {
    let that = this
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid,
          orderId: that.options.orderId
        }, () => {
          that.orderDetail();
        })
      }
    })
  },
  orderDetail() {
  
    let that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderNo: that.data.orderId
    }
    common.post("/crowdfunding/getOrderDetail", tempJson, function (res) {
      var arr =[]
      arr = [res.data]
      that.setData({
        orderInfo:arr
      })
    })
  },
  onChange(event) {
    console.log(event.currentTarget.dataset.index)
    let index = event.currentTarget.dataset.index
    this.setData({
      ['star' + index]: event.detail
    });
  },
  onChangeContent(event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      ['content' + index]: event.detail.value
    })
  },
  saveComment() {
    const that = this
    const orderInfo = that.data.orderInfo
    const totalNum = orderInfo.length
    // 检查是否输入了评价
    for (let i = 0; i < totalNum; i++) {
      const content = this.data['content' + i]
      if (content === null || content === undefined || content.length === 0) {
        common.showToast('请输入商品评价')
        return
      }
    }

    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderNo:that.data.orderInfo[0].orderNo,
      crowdfundingId:that.data.orderInfo[0].crowdfundingId,
      commentMsg:this.data['content' + 0]
    }

    // orderInfo.map((item, index) => {
    //   tempJson['list[' + index + '].userId'] = this.data.userInfo.id
    //   tempJson['list[' + index + '].orderNo'] = this.data.orderInfo[index].orderNo
    //   tempJson['list[' + index + '].crowdfundingId'] = this.data.orderInfo[index].crowdfundingId
    //   tempJson['list[' + index + '].content'] = this.data['content' + index]
    //   tempJson['list[' + index + '].star'] = this.data['star' + index]
    //   that.data.fileList != '' && that.data.fileList[index].map((file, n) => {
    //     tempJson['list[' + index + '].pic[' + n + ']'] = file.data
    //   })
    // })
    console.log(tempJson)
    common.post('/crowdfundingComment/addComment', tempJson, function (res) {
      if (res.msg == "评论成功") {
        wx.navigateBack({
          delta: 1,
          complete: (res) => {
            common.showToast('评论成功')
          },
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },

  deletePic(e) {
    // 由于评论返回的是数组，这里需要先获取到当前商品
    const index = e.currentTarget.dataset.index
    const order = e.currentTarget.dataset.order // 订单商品索引
    const fileList = this.data.fileList
    const imgList = fileList[order] ? fileList[order] : []
    try {
      imgList.splice(index, 1)
      fileList[index] = imgList
      this.setData({
        fileList
      })
    } catch (error) {
      console.log(error)
    }
  },

  chooseimage(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const fileList = this.data.fileList
    const imgList = fileList[index] ? fileList[index] : []
    wx.chooseImage({
      count: 3 - imgList.length, // 默认9  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        that.uploadFiles(res, index)
      }
    })
  },
  async uploadFiles(res, index) {
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
    const fileList = this.data.fileList
    const imgList = fileList[index] ? fileList[index] : []

    const fileSystemManager = wx.getFileSystemManager()
    for (let path of res.tempFilePaths) {
      const readFile = this.promisify(fileSystemManager.readFile)
      let {
        data
      } = await readFile({
        filePath: path,
        encoding: 'base64'
      })
      imgList.push({
        path,
        data
      })
    }

    fileList[index] = imgList
    console.log(fileList)
    this.setData({
      fileList
    })
  },
  promisify(api) {
    return (options, ...params) => {
      return new Promise((resolve, reject) => {
        api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
      });
    }
  }
})